package hnair.com.shop.app;

import com.joanzapata.iconify.IconFontDescriptor;
import com.joanzapata.iconify.Iconify;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by liaowei on 2017/11/16.
 * 配置信息类
 */

public class Configurator {

    private static final HashMap<String, Object> SHOP_CONFIGS = new HashMap<>();
    //封装字体图标的使用
    private static final ArrayList<IconFontDescriptor> ICONS = new ArrayList<>();

    private Configurator() {
        SHOP_CONFIGS.put(ConfigType.CONFIG_READ.name(), false);
    }

    public static Configurator getInstance() {
        return Holder.INSTANCE;
    }

    public final void configure() {
        initIcons();
        SHOP_CONFIGS.put(ConfigType.CONFIG_READ.name(), true);
    }

    public final Configurator withApiHost(String host) {
        SHOP_CONFIGS.put(ConfigType.API_HOST.name(), host);
        return this;
    }

    private void initIcons() {
        if (ICONS.size() > 0) {
            //已存在图标
            final Iconify.IconifyInitializer initializer = Iconify.with(ICONS.get(0));
            //从1开始
            for (int i = 1; i < ICONS.size(); i++) {
                initializer.with(ICONS.get(i));
            }
        }
    }

    //加入自己的字体图标
    public final Configurator withIcon(IconFontDescriptor descriptor) {
        ICONS.add(descriptor);
        return this;
    }

    final HashMap<String, Object> getShopConfigs() {
        return SHOP_CONFIGS;
    }

    //单例模式，静态内部类实现
    private static class Holder {
        private static final Configurator INSTANCE = new Configurator();

    }


    //检查配置是否完成
    private void checkConfiguration() {
        final boolean isReady = (boolean) SHOP_CONFIGS.get(ConfigType.CONFIG_READ.name());
        if (!isReady) {
            throw new RuntimeException("Configuration is not ready, call configure");
        }
    }

    @SuppressWarnings("unchecked")
    final <T> T getConfiguration(Enum<ConfigType> key) {
        checkConfiguration();
        return (T) SHOP_CONFIGS.get(key.name());
    }

}
